<?php
class FileUpload
{
	const DEFAULT_FIELD_NAME = 'file';
	
	private $fieldName;
	private $allowedExtensions;
	
	public function __construct($fieldName = null)
	{
		$this->fieldName = $fieldName ? $fieldName : self::DEFAULT_FIELD_NAME;
	}
	
	public function __get($paramName)
	{
		if($_FILES && $_FILES[$this->fieldName]){
			return $_FILES[$this->fieldName][$paramName];
		}
		return null;
	}
	
	public function setAllowedExtensions(array $allowedExtensions)
	{
		$this->allowedExtensions = $allowedExtensions;
	}
	
	public function getFormHtml()
	{
		ob_start();
		?>
			<form action="index.php" method="post" enctype="multipart/form-data" >
				<p>
					<label>Select File</label>
					<input type="file" name="<?php echo $this->fieldName;?>" value="" />
				</p>
				<p>
					<input type="submit" value="upload"  />
				</p>
			</form>
		<?php
		$html = ob_get_contents();
		ob_get_clean();
		return $html;
	}
	
	public function getErrorMessage()
	{
		return $this->errorMessage;
	}
	
	public function getFileName()
	{
		$nameArr = explode('.', $this->name);
		unset($nameArr[count($nameArr) -1]);
		return implode('.', $nameArr);
	}
	
	public function getFileData()
	{
		$data = array();
		$data['name'] = $this->getFileName();
		$data['type'] = $this->type;
		$data['data'] = file_get_contents($this->tmp_name);
		return $data;
	}
	
	public function isUploadedFile()
	{
		$isUploadedFile = false;
		if(is_uploaded_file($this->tmp_name)){
			if($this->error == UPLOAD_ERR_OK){
				$extArr = explode('/', $this->type);
				$ext = $extArr[count($extArr)-1];
				if(in_array($ext, $this->allowedExtensions)){
					$isUploadedFile = true;
				}
			}
		}
		if(!$isUploadedFile){
			$this->errorMessage = 'Upload faild';
		}
		return $isUploadedFile;
	}
	
	public function __destruct()
	{
		if($this->tmp_name){
			unlink($this->tmp_name);
		}
		unset($this);
	}
}